package com.yunhui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunhui.entity.*;
import com.yunhui.mapper.OrderMapper;
import com.yunhui.service.OrderService;
import com.yunhui.service.RouteIssuedService;
import com.yunhui.service.RouteJbService;
import com.yunhui.util.Constants;
import com.yunhui.util.PageSupport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  订单的前端控制层
 * </p>
 *
 * @author WGH
 * @since 2019-12-09
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    //出行人数
    private  Integer peopleCount = 0;


/****************************************************后台：订单页面****************************************************/
    /**
     * 去订单页面,并显示所有订单信息
     * @return
     */
//    @RequestMapping("/goOrder")
//    public String goOrder(){
//        return "/houtai/order";
//    }

    @RequestMapping("/goOrder")
    public ModelAndView findAllOrder(ModelAndView modelAndView){
//        Integer pageNo = Integer.valueOf(1);
//        Integer pageSize = Integer.valueOf(5);
//        IPage<Order> page = new Page<>();
        List<Order> orderList = orderService.findAllOrder();
        int orderCount = orderService.count(null);
        System.out.println("所有订单信息："+orderList);

        //查询所有记录数
        modelAndView.addObject("orderList",orderList);
        //查询总条数
        modelAndView.addObject("orderCount",orderCount);

        //指定页面名称
        modelAndView.setViewName("/houtai/order");
        return  modelAndView;
    }

    /**
     * 后台
     * 根据用户Id分页查询订单信息
     * @param modelAndView
     * @param request
     * @param uid   用户Id
     * @param sid   商家Id
     * @param pageIndex 第几页
     * @return
     */
    @RequestMapping("/findOrderByUid")
    public ModelAndView findOrderByUid(ModelAndView modelAndView, HttpServletRequest request,String uid,String sid,String pageIndex,String startTime){
        //String orderDate = request.getParameter("startTime");
        //当前第几页（从0开始算）
        Integer index= 0;
        if(pageIndex!=null){
            index=Integer.parseInt(pageIndex);
        }
        Integer userId = 0;
        Integer shangjiaId = 0;
        String startDate = "";
        uid = request.getParameter("username");
        sid = request.getParameter("ordersid");
        System.err.println("订单日期："+startTime+",用户Id:"+uid+",商家Id:"+sid);
        if(startTime != null && startTime != ""){
            startDate = startTime;
        }
        if(uid != null && uid != "") {
            userId = Integer.valueOf(uid);
        }
        if(sid != null && sid != "") {
            shangjiaId = Integer.valueOf(sid);
        }
        List<Order> orderByUid = orderService.findOrderById(startDate,shangjiaId,userId,index,Constants.pageSize);
        //创建分页对象
        PageSupport page  = new PageSupport();
        //当前页码
        page.setCurrentPageNo(index);
        //每一页显示的数量
        page.setPageSize(Constants.pageSize);

        //查询总条数
        Integer orderCount = orderService.count(null);
        modelAndView.addObject("orderCount",orderCount);

        //最后获取总页数
        Integer totalPageCount = 0;
        if(orderCount%Constants.pageSize ==0){
            totalPageCount = orderCount/Constants.pageSize;
        }else if(orderCount%Constants.pageSize >0){
            totalPageCount = orderCount/Constants.pageSize+1;
        }

        //测试
        System.out.println("根据用户id所查数据："+orderByUid);

        System.err.println("用户Id："+userId+",商家Id"+shangjiaId+",总页数："+totalPageCount+",当前页数："+index);
        //返回结果
        modelAndView.addObject("orderList",orderByUid);
        modelAndView.addObject("currentPageNo",index);  //当前第几页
        modelAndView.addObject("totalPageCount",totalPageCount);    //总页数
        modelAndView.addObject("page",page);
        modelAndView.setViewName("/houtai/order");
        return modelAndView;
    }

    /**
     *
     * 查看详细信息
     * @param request
     * @param modelAndView
     * @param oid
     * @param
     * @return
     */
    @RequestMapping("/goshowInfo")
    public ModelAndView goshowInfo(HttpServletRequest request,ModelAndView modelAndView,String oid
            ,Integer ostatus,String oprice,Integer sid){
        Integer orderId = 0 ;   //订单编号
        String status = "";     //订单状态

        if(oid != null && oid != ""){
            orderId = Integer.valueOf(oid);
        }
        if(ostatus != null ){
            if(ostatus == 1){
                status = "已付款";
            }else if(ostatus == 2){
                status = "未付款";
            }
        }

        peopleCount = 2;
        //Integer jbId = orderService.findRoute_issued(sid);
        //System.err.println(jbId);
        //List<RouteJb> routeList = orderService.findRouteInfo(jbId);

        List<SubscribePeople> subscribePeople = orderService.findSubscribePeople(orderId);

        List<PeopleInfo> peopleInfos = orderService.findPeopleInfo(orderId);

        modelAndView.addObject("subscribePeopleList",subscribePeople);
        modelAndView.addObject("peopleInfoList",peopleInfos);

        modelAndView.addObject("peopleCount",peopleCount);  //人数
        //modelAndView.addObject("routeList",routeList);
        modelAndView.addObject("oprice",oprice);            //价格
        modelAndView.addObject("status",status);            //订单状态
        modelAndView.addObject("orderId",orderId);          //订单编号
        modelAndView.setViewName("/houtai/showInfo");
        return modelAndView;
    }


/****************************************************后台：商家页面****************************************************/
        @Resource
        private RouteJbService routeJbService;

    /**
     * 商家
     * 根据商家登录的Id分页查询订单信息
     * @param modelAndView
     * @param request
     * @param sjId   商家登录时的Id
     * @param pageIndex 第几页
     * @return
     */
    @RequestMapping("/findOrderBysjId")
    public ModelAndView findOrderBysjId(ModelAndView modelAndView, HttpServletRequest request,
                                        String startTime,String title,Integer sjId,String pageIndex){
        //当前第几页（从0开始算）
        Integer index= 0;
        //商家登录id
        sjId = 0001;
        Merchant m = (Merchant) request.getSession().getAttribute("merchant");
        if(pageIndex!=null){
            index=Integer.parseInt(pageIndex);
        }
        String startDate = "";
        if(startTime != null && startTime != ""){
            startDate = startTime;
        }


        //获取下拉框的值
        title=  request.getParameter("tablename");
        System.err.println(title);



        //参数顺序要一致
        List<Order> orderByUid = orderService.findOrderBysjId(startDate,title,m.getId(),index,Constants.pageSize);

        /**
         * 商家
         * 查詢今日訂單
         */
        //当前商家登录时的id
        List<Order> orderTodayList = orderService.findTodayOrder(m.getId());
        System.out.println("今日订单信息："+orderTodayList);
        modelAndView.addObject("orderTodayList",orderTodayList);

        /**
         * 商家
         * 加载行程信息
         */
        List<RouteJb> routeJbs = routeJbService.list(new QueryWrapper<RouteJb>().eq("mId",m.getId()));
        modelAndView.addObject("routeJbs",routeJbs);


        //创建分页对象
        PageSupport page  = new PageSupport();
        //当前页码
        page.setCurrentPageNo(index);
        //每一页显示的数量
        page.setPageSize(Constants.pageSize);

        //查询总条数
        Integer orderCount = orderService.count(null);
        modelAndView.addObject("orderCount",orderCount);

        //最后获取总页数
        Integer totalPageCount = 0;
        if(orderCount%Constants.pageSize ==0){
            totalPageCount = orderCount/Constants.pageSize;
        }else if(orderCount%Constants.pageSize >0){
            totalPageCount = orderCount/Constants.pageSize+1;
        }

        //测试
        System.out.println("根据用户id所查数据："+orderByUid);

        System.err.println("行程发布id:"+title+",总页数："+totalPageCount+",当前页数："+index);
        //返回结果
        modelAndView.addObject("orderList",orderByUid);
        modelAndView.addObject("currentPageNo",index);  //当前第几页
        modelAndView.addObject("totalPageCount",totalPageCount);    //总页数

        modelAndView.setViewName("/shang/order");
        return modelAndView;
    }

/****************************************************前台：订单页面****************************************************/

    /**
     *
     * 去订单页面
     */
    @Resource
    private RouteIssuedService routeIssuedService;




    /**
     * 跳转订单页面
     * @param model
     * @param jbid
     * @param session
     * @return
     */
    @RequestMapping("/order")
    public String  goOrder(Model model, Integer jbid,HttpSession session,String numer){
        //查询行程信息
      //  List<RouteJb> routeList = orderService.findRouteInfo(7);
        User user = (User)session.getAttribute("LoginUser");
        if(user==null){
            return "/login/login_sign";
        }

       RouteIssued rf= routeIssuedService.getById(jbid);
       RouteJb r =  routeJbService.getById(rf.getJbId());
      //  System.out.println(routeList);
        //出发人数
        peopleCount = Integer.parseInt(numer);
        BigDecimal price = r.getPrice().multiply(new BigDecimal(peopleCount));


        model.addAttribute("price",price);

        model.addAttribute("title",r.getTitle());
        model.addAttribute("qidian",r.getOrigin());
        model.addAttribute("rbid",jbid);

        model.addAttribute("time",rf.getStartTimes());
       // model.addAttribute("",r.getTitle());
        model.addAttribute("peopleCount",peopleCount);
        model.addAttribute("r",r);
        model.addAttribute("r",rf);
        System.err.println(r);
        System.err.println(rf);
     //  modelAndView.setViewName("/order");
        //modelAndView.setViewName("/出境合同.html");
        return "/order";
    }


    /**
     *
     *添加联系人，出行人信息，添加订单信息等 使用
     * 添加游客信息
     */
    @Resource
    OrderMapper orderMapper ;
    @RequestMapping("/addOrder")
    public  ModelAndView addOrder(ModelAndView modelAndView,String peopleCount, SubscribePeople subscribePeople
            , String Sp_name, String Sp_phone, String Sp_email, String Remark
            , PeopleInfo peopleInfo, String tname, String tphone, String tcard, String sex,String price,String rbid,HttpSession session){

        //获取user对象获取id
        User user = (User) session.getAttribute("LoginUser");
        if(user==null){
            modelAndView.setViewName("redirect:login_sign");
            return  modelAndView;

        }


        //订单对象
        Order order = new Order();
        order.setPrice(new BigDecimal(price));
        order.setUid(user.getId());
        order.setSid(Integer.parseInt(rbid));
        order.setO_date(new Date());
        order.setStatus(1);
       //orderMapper.insert(order);



        //联系人对象
        subscribePeople.setO_id(order.getId());
        subscribePeople.setSp_name(Sp_name);
        subscribePeople.setSp_phone(Sp_phone);
        subscribePeople.setSp_email(Sp_email);
        subscribePeople.setRemark(Remark);
       // int count = orderService.addSubscribePeople(subscribePeople);
      //  System.err.println(Sp_name+","+Sp_phone+","+Sp_email+","+Remark+count);

        //联系人的对象
        List<PeopleInfo> list = new ArrayList<>();
        //添加游客
        //获取出行人数
        int num = Integer.parseInt(peopleCount);
        peopleInfo.setO_id(order.getId());
        String peopleName[]  = tname.split(",");
        String peoplePhone[] = tphone.split(",");
        String peopleCard[] = tcard.split(",");
        peopleInfo.setP_sex(sex);
        for (int i=0;i<num;i++){

            peopleInfo.setP_name(peopleName[i]);


            peopleInfo.setP_phone(peoplePhone[i]);


            peopleInfo.setP_number(peopleCard[i]);


            //int count1 = orderService.addPeopleInfo(peopleInfo);
            list.add(peopleInfo);
           // System.err.println("乘客姓名："+peopleName[i]+"联系电话："+peoplePhone[i]+"身份证号："+peopleCard[i]+"性别："+sex+","+count1);
        }


        if( orderService.addOrder(order,subscribePeople,list)){
            System.err.println("添加成功");
        }

        modelAndView.setViewName("redirect:/order/myorder");
        return modelAndView;
    }


    /**
     *
     * 前台订单详细显示页面
     */
    @RequestMapping("/goShowOrder")
    public ModelAndView goShowOrder(HttpServletRequest request,ModelAndView modelAndView,String id) {
        Integer orderId = 0;   //订单编号
       // String status = "";     //订单状态

        if (id != null && id != "") {
            orderId = Integer.valueOf(id);
        }

        List<Order> orderInfo = orderService.findInfo(orderId);

        //联系人，游客详细
        List<SubscribePeople> subscribePeople = orderService.findSubscribePeople(orderId);
        List<PeopleInfo> peopleInfos = orderService.findPeopleInfo(orderId);
        modelAndView.addObject("subscribePeopleList", subscribePeople);
        modelAndView.addObject("peopleInfoList", peopleInfos);

        modelAndView.addObject("orderInfo",orderInfo);
        //modelAndView.addObject("routeList",routeList);

        modelAndView.addObject("orderId", orderId);          //订单编号
        modelAndView.setViewName("/showInfo");
        return modelAndView;
    }


    /**
     *
     * 修改联系人信息
     */
    @RequestMapping("/upSpInfo")
    public ModelAndView upSpInfo(ModelAndView modelAndView,String txtName,String txtNumber,String txtEmail,Integer oid){
        System.err.println(txtName+txtNumber+txtEmail+oid);
        SubscribePeople subscribePeople = new SubscribePeople();
        subscribePeople.setSp_name(txtName);
        subscribePeople.setSp_phone(txtNumber);
        subscribePeople.setSp_email(txtEmail);
        subscribePeople.setO_id(oid);
        int count = orderService.updateSubscribePeople(subscribePeople);
        if(count>0){
            modelAndView.addObject("id",oid);
            modelAndView.setViewName("redirect:goShowOrder");

        }
        return modelAndView;
    }









/****************************************************前台：我的订单页面****************************************************/
    /**
     *有问题！
     * 前台：我的订单
     * @param index
     * @param status
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("myorder")
    public String myorder(String index,String status, Model model, HttpSession session){
        //当前登录的用户id
        Integer uid = 1;
        //判断当前页码
        Integer indext = 1;
        if(index!=null&& index!=""){
            if(!index.equals("null")){
                indext = Integer.parseInt(index);
            }

        }

        System.err.println(index);
        System.err.println(status);
        if("null".equals(status)){
            status=null;
        }

        //总数分页
        PageSupport page = new PageSupport();

        System.err.println(orderService.CountByPage(null,uid));
        page.setTotalCount(orderService.CountByPage(null,uid));
        page.setCurrentPageNo(indext);
        //待付款分页
        PageSupport moneypage =new PageSupport();
        moneypage.setTotalCount(orderService.CountByPage("1",uid));
        moneypage.setCurrentPageNo(indext);
        //待出行分页
        PageSupport trippage =new PageSupport();
        trippage.setTotalCount(orderService.CountByPage("2",uid));
        trippage.setCurrentPageNo(indext);
        //已完成分页
        PageSupport overpage =new PageSupport();
        overpage.setTotalCount(orderService.CountByPage("3",uid));
        overpage.setCurrentPageNo(indext);

        Integer countpage = 0;
        if(status==null){
            countpage = page.getTotalPageCount();
        }else if(status.equals("1")){
            countpage = moneypage.getTotalPageCount();
        }else if(status.equals("2")){
            countpage = trippage.getTotalPageCount();
        }else if(status.equals("3")){
            countpage = overpage.getTotalPageCount();
        }


        List<Order> list = orderService.ListByPage(indext,page.getPageSize(),status,uid);
        model.addAttribute("order_list",list);
        model.addAttribute("trippage",trippage);
        model.addAttribute("moneypage",moneypage);
        model.addAttribute("overpage",overpage);
        model.addAttribute("page",page);
        model.addAttribute("status",status);
        model.addAttribute("countpage",countpage);
        model.addAttribute("index",indext);
        return "my_oder";
    }

}

